package com.nullam.lorem.contactsync.adaptor;

import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nullam.lorem.contactsync.R;
import com.nullam.lorem.contactsync.data.Contact;

public class ListViewAdapter extends ArrayAdapter<Contact> {

	private final Context context;
	private final List<Contact> contacts;

	public ListViewAdapter(Context context, List<Contact> contacts) {
		super(context, R.layout.contacts_list_item, contacts);
		this.context = context;
		this.contacts = contacts;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return contacts.size();
	}

	@SuppressLint("ViewHolder")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(R.layout.contacts_list_item, parent,
				false);
		TextView displayName = (TextView) rowView
				.findViewById(R.id.item_display_name);
		TextView information = (TextView) rowView
				.findViewById(R.id.item_phone_number);
		ImageView contactImage = (ImageView) rowView
				.findViewById(R.id.ContactImage);
		contactImage = (ImageView) rowView.findViewById(R.id.ContactImage);
		Bitmap photoBitmap = contacts.get(position).getPhotoId();
		if (photoBitmap != null) {
			contactImage.setImageBitmap(photoBitmap);
			// contactImage.setImageResource(android.R.drawable.ic_menu_camera);
		} else {
			contactImage.setImageResource(R.drawable.contact_icon);
		}

		displayName.setText(contacts.get(position).getDisplayName());
		HashMap<String, String> phoneNumbers = contacts.get(position)
				.getPhoneNumbers();
		HashMap<String, String> emails = contacts.get(position)
				.getEmails();
		if (phoneNumbers != null && phoneNumbers.size() > 0) {
			String firstPhoneNumber = (String) phoneNumbers.keySet().toArray()[0];
			String firstPhoneNumberType = phoneNumbers.get(firstPhoneNumber);
			information
					.setText(firstPhoneNumberType + " : " + firstPhoneNumber);
		} else if (emails != null && emails.size() > 0){
			String firstEmail = (String) emails.keySet().toArray()[0];
			String firstEmailType = emails.get(firstEmail);
			information
					.setText(firstEmailType + " : " + firstEmail);
		}else{
			information
			.setText("No other information");
		}

		return rowView;
	}

}